// 配置marked以支持代码高亮
window.module.marked.setOptions({
  highlight: function (code, language) {
    if (language && window.module.hljs.getLanguage(language)) {
      return window.module.hljs.highlight(code, { language }).value;
    }
    return window.module.hljs.highlightAuto(code).value;
  },
  breaks: true,
  gfm: true
});

// 设置组件实例
let settingsModel = null;
// Header组件实例
let appHeader = null;
// Header处理器实例
let headerHandlers = null;
// 主聊天组件实例
let appMainChat = null;
// 文档管理组件实例
let appMainDocument = null;
// 工作流组件实例
let appMainWorkflow = null;
// 当前视图状态
let currentView = 'chat';

// 设置管理
// 初始化设置组件和头部组件
document.addEventListener('DOMContentLoaded', async () => {
  // 创建头部组件实例
  appHeader = new AppHeader();
  await appHeader.init();

  // 创建头部处理器实例并初始化用户ID
  headerHandlers = new HeaderHandlers();
  await headerHandlers.init(appHeader);

  // 创建主聊天组件实例
  appMainChat = new AppMainChat();
  await appMainChat.init();
  // 创建文档管理组件实例
  appMainDocument = new AppMainDocument();
  await appMainDocument.init();
  // 创建工作流组件实例
  appMainWorkflow = new AppMainWorkflow();
  await appMainWorkflow.init();
  
  // 设置全局实例供属性面板使用
  window.appMainWorkflow = appMainWorkflow;

  // 创建设置组件实例
  settingsModel = new SettingsModel();
  await settingsModel.init();

  // 将设置模型传递给头部组件
  appHeader.setSettingsModel(settingsModel);

  // 监听设置更新事件 - 传递给主聊天组件
  document.addEventListener('settingsUpdated', (e) => {
    if (appMainChat) {
      appMainChat.updateSettings(e.detail);
    }
  });

  // 监听视图切换事件
  document.addEventListener('viewChanged', (e) => {
    switchView(e.detail.view);
  });

  // 默认显示聊天视图
  switchView('chat');
});

// 辅助函数：格式化文件大小
function formatSize(bytes) {
  if (bytes === 0) return '0 B';

  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));

  return parseFloat((bytes / Math.pow(1024, i)).toFixed(2)) + ' ' + sizes[i];
}

// 显示通知消息
function showNotification(message, type = 'info') {
  // 移除现有的通知
  const existingNotification = document.querySelector('.notification');
  if (existingNotification) {
    existingNotification.remove();
  }

  const notification = document.createElement('div');
  notification.className = `notification notification-${type}`;

  let icon = '';
  switch (type) {
    case 'success': icon = '✅'; break;
    case 'error': icon = '❌'; break;
    case 'warning': icon = '⚠️'; break;
    default: icon = 'ℹ️'; break;
  }

  notification.innerHTML = `
    <span class="notification-icon">${icon}</span>
    <span class="notification-message">${message}</span>
    <button class="notification-close" onclick="this.parentElement.remove()">&times;</button>
  `;

  document.body.appendChild(notification);

  // 自动消失
  setTimeout(() => {
    if (notification.parentElement) {
      notification.classList.add('notification-hide');
      setTimeout(() => notification.remove(), 300);
    }
  }, 3000);
}

// 让全局可访问，供设置组件使用
window.showNotification = showNotification;
window.formatSize = formatSize;

// 视图切换函数
function switchView(view) {
  if (currentView === view) return;

  // 隐藏当前视图
  if (currentView === 'chat' && appMainChat) {
    appMainChat.hide();
  } else if (currentView === 'document' && appMainDocument) {
    appMainDocument.hide();
  } else if (currentView === 'workflow' && appMainWorkflow) {
    appMainWorkflow.hide();
  }

  // 显示新视图
  if (view === 'chat' && appMainChat) {
    appMainChat.show();
  } else if (view === 'document' && appMainDocument) {
    appMainDocument.show();
  } else if (view === 'workflow' && appMainWorkflow) {
    appMainWorkflow.show();
  }

  currentView = view;
  console.log(`Switched to ${view} view`);
}
